<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>任务管理 - 小红书搜索工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #ff6b6b 0%, #ffa726 100%);
            color: white;
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            font-size: 28px;
            font-weight: 600;
        }

        .nav-links {
            display: flex;
            gap: 15px;
        }

        .nav-links a {
            color: white;
            text-decoration: none;
            padding: 8px 16px;
            border-radius: 20px;
            background: rgba(255, 255, 255, 0.2);
            transition: all 0.3s ease;
        }

        .nav-links a:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .nav-links a.active {
            background: rgba(255, 255, 255, 0.4);
        }

        .user-info {
            position: relative;
        }

        .user-phone {
            background: rgba(255, 255, 255, 0.2);
            padding: 8px 16px;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .user-phone:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .dropdown {
            position: absolute;
            top: 100%;
            right: 0;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            min-width: 120px;
            z-index: 1000;
            display: none;
        }

        .dropdown.show {
            display: block;
        }

        .dropdown-item {
            padding: 12px 16px;
            color: #333;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .dropdown-item:hover {
            background: #f8f9fa;
        }

        .main-content {
            padding: 30px;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 15px;
        }

        .toolbar h2 {
            color: #333;
            margin: 0;
        }

        .toolbar-actions {
            display: flex;
            gap: 15px;
        }

        .filter-section {
            background: white;
            padding: 20px;
            border-radius: 15px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .filter-row {
            display: flex;
            gap: 20px;
            align-items: center;
            flex-wrap: wrap;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .filter-group label {
            font-weight: 600;
            color: #333;
            font-size: 14px;
        }

        .filter-group select {
            padding: 8px 12px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            min-width: 120px;
        }

        .filter-group select:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(78, 205, 196, 0.4);
        }

        .btn-warning {
            background: linear-gradient(135deg, #ffa726 0%, #ff7043 100%);
            color: white;
        }

        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 167, 38, 0.4);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 107, 107, 0.4);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
            color: white;
        }

        .btn-secondary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(108, 117, 125, 0.4);
        }

        .btn-small {
            padding: 6px 12px;
            font-size: 12px;
        }

        .create-task-form {
            background: white;
            padding: 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-group input, .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .form-group input:focus, .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-group small {
            color: #666;
            font-size: 12px;
            margin-top: 5px;
            display: block;
        }

        .task-list {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .task-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            border-left: 4px solid #667eea;
        }

        .task-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .task-name {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }

        .task-status-group {
            display: flex;
            gap: 8px;
        }

        .task-status, .task-enabled {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-pending { background: #fff3cd; color: #856404; }
        .status-running { background: #d4edda; color: #155724; }
        .status-completed { background: #d1ecf1; color: #0c5460; }
        .status-failed { background: #f8d7da; color: #721c24; }

        .status-enabled { background: #d4edda; color: #155724; }
        .status-disabled { background: #f8d7da; color: #721c24; }

        .task-info {
            color: #666;
            font-size: 14px;
            margin-bottom: 5px;
        }

        .task-keywords {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            margin: 10px 0;
        }

        .keyword-tag {
            background: #e9ecef;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 12px;
            color: #495057;
        }

        .task-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 20px;
        }

        .pagination button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .pagination button:hover {
            background: #f8f9fa;
        }

        .pagination button.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .hidden {
            display: none !important;
        }

        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }

        /* 弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            max-width: 500px;
            width: 90%;
            background: white;
            border-radius: 10px;
            padding: 0;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-bottom: 1px solid #eee;
        }

        .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }

        .close {
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #999;
            line-height: 1;
        }

        .close:hover {
            color: #333;
        }

        .modal-body {
            padding: 20px;
        }

        .modal-body label {
            display: block;
            margin-bottom: 10px;
            font-weight: 600;
            color: #333;
        }

        .modal-body textarea {
            width: 100%;
            padding: 10px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            resize: vertical;
            font-family: inherit;
        }

        .modal-body textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            padding: 20px;
            border-top: 1px solid #eee;
        }

        .error {
            color: #dc3545;
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
        }

        .success {
            color: #155724;
            background: #d4edda;
            border: 1px solid #c3e6cb;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
        }

        @media (max-width: 768px) {
            .filter-row {
                flex-direction: column;
                gap: 15px;
            }
            
            .filter-row[style*="justify-content: flex-start"] {
                flex-direction: row;
                flex-wrap: wrap;
                gap: 10px;
                justify-content: flex-start !important;
            }
            
            .filter-row[style*="justify-content: flex-start"] .btn {
                flex: 1;
                min-width: 100px;
                margin: 0 !important;
            }
            
            .task-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;
            }
            
            .task-actions {
                flex-wrap: wrap;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>小红书搜索工具 - 任务管理</h1>
            <div class="nav-links">
                <a href="index.html">首页</a>
                <a href="task.html" class="active">任务管理</a>
                <a href="result.html">执行结果</a>
            </div>
            <div class="user-info">
                <div class="user-phone" id="userPhone" onclick="toggleDropdown()">
                    未登录
                </div>
                <div class="dropdown" id="dropdown">
                    <div class="dropdown-item" onclick="logout()">退出登录</div>
                </div>
            </div>
        </div>

        <div class="main-content">
            <!-- 任务筛选 -->
            <div class="filter-section">
                <h3 style="margin-bottom: 15px; color: #333;">任务筛选</h3>
                <div class="filter-row">
                    <div class="filter-group">
                        <label for="statusFilter">任务状态</label>
                        <select id="statusFilter" onchange="applyFilters()">
                            <option value="">全部状态</option>
                            <option value="PENDING">待执行</option>
                            <option value="RUNNING">执行中</option>
                            <option value="COMPLETED">已完成</option>
                            <option value="FAILED">失败</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label for="enabledFilter">启用状态</label>
                        <select id="enabledFilter" onchange="applyFilters()">
                            <option value="">全部</option>
                            <option value="1">启用</option>
                            <option value="0">禁用</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label for="sortFilter">排序方式</label>
                        <select id="sortFilter" onchange="applyFilters()">
                            <option value="create_time_desc">创建时间(最新)</option>
                            <option value="create_time_asc">创建时间(最旧)</option>
                            <option value="update_time_desc">更新时间(最新)</option>
                            <option value="task_name_asc">任务名称(A-Z)</option>
                        </select>
                    </div>
                </div>
                <div class="filter-row" style="margin-top: 15px; justify-content: flex-start;">
                    <button class="btn btn-secondary" onclick="clearFilters()">清空筛选</button>
                    <button class="btn btn-success" onclick="refreshTasks()" style="margin-left: 10px;">刷新任务</button>
                    <button class="btn btn-primary" onclick="openCreateTaskModal()" style="margin-left: 10px;">创建任务</button>
                </div>
            </div>



            <!-- 任务列表 -->
            <div class="task-list">
                <div id="tasksList">
                    <!-- 任务列表将在这里显示 -->
                </div>
                
                <!-- 分页 -->
                <div class="pagination" id="pagination">
                    <!-- 分页按钮将在这里显示 -->
                </div>
            </div>
        </div>
    </div>

    <!-- 创建任务弹窗 -->
    <div id="createTaskModal" class="modal">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <div class="modal-title">创建搜索任务</div>
                <span class="close" onclick="closeCreateTaskModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="createTaskName">任务名称</label>
                    <input type="text" id="createTaskName" placeholder="请输入任务名称">
                </div>
                <div class="form-group">
                    <label for="createKeywords">搜索关键词</label>
                    <textarea id="createKeywords" rows="3" placeholder="请输入关键词，多个关键词用中文逗号分隔"></textarea>
                    <small>例如：小学 群，幼小 群，家长 群，初中 群，小升初 群</small>
                </div>
                <div class="form-group">
                    <label for="createExecuteInterval">执行间隔（分钟）</label>
                    <input type="number" id="createExecuteInterval" min="1" value="10" placeholder="请输入执行间隔分钟数">
                    <small>任务自动执行的间隔时间，单位：分钟，最小1分钟</small>
                </div>
                <div class="form-group">
                    <label for="createPostTimeLimit">帖子时间限制（天）</label>
                    <input type="number" id="createPostTimeLimit" min="1" value="4" placeholder="请输入帖子时间限制天数">
                    <small>只记录发布时间在此天数内的帖子，超过时间的帖子将被忽略</small>
                </div>
                <div class="form-group">
                    <label for="createSearchPages">搜索页数</label>
                    <input type="number" id="createSearchPages" min="1" max="10" value="1" placeholder="请输入搜索页数">
                    <small>每页查20条数据，建议不超过10页以避免过长的搜索时间</small>
                </div>
                <div id="createTaskMessage"></div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary" onclick="createTask()">创建任务</button>
                <button class="btn btn-secondary" onclick="closeCreateTaskModal()">取消</button>
            </div>
        </div>
    </div>

    <!-- 修改任务弹窗 -->
    <div id="editTaskModal" class="modal">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <div class="modal-title">修改任务</div>
                <span class="close" onclick="closeEditTaskModal()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="editTaskName">任务名称</label>
                    <input type="text" id="editTaskName" readonly style="background-color: #f8f9fa;">
                </div>
                <div class="form-group">
                    <label for="editKeywords">搜索关键词</label>
                    <textarea id="editKeywords" rows="4" placeholder="请输入关键词，用逗号分隔"></textarea>
                </div>
                <div class="form-group">
                    <label for="editExecuteInterval">执行间隔（分钟）</label>
                    <input type="number" id="editExecuteInterval" min="1" placeholder="请输入执行间隔分钟数">
                </div>
                <div class="form-group">
                    <label for="editPostTimeLimit">帖子时间限制（天）</label>
                    <input type="number" id="editPostTimeLimit" min="1" placeholder="请输入帖子时间限制天数">
                </div>
                <div class="form-group">
                    <label for="editSearchPages">搜索页数</label>
                    <input type="number" id="editSearchPages" min="1" max="10" placeholder="请输入搜索页数">
                    <small>每页查20条数据，建议不超过10页以避免过长的搜索时间</small>
                </div>
                <div id="editTaskMessage"></div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary" onclick="saveTaskChanges()">保存修改</button>
                <button class="btn btn-secondary" onclick="closeEditTaskModal()">取消</button>
            </div>
        </div>
    </div>

    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 1;
        let allTasks = []; // 存储所有任务数据
        let filteredTasks = []; // 存储筛选后的任务数据
        
        // 页面加载时检查登录状态
        window.onload = function() {
            checkLoginStatus();
        };

        // 检查登录状态
        function checkLoginStatus() {
            const phoneNumber = localStorage.getItem('phoneNumber');
            if (phoneNumber) {
                document.getElementById('userPhone').textContent = phoneNumber;
                loadTasks();
            } else {
                alert('请先登录');
                window.location.href = 'index.html';
            }
        }

        // 切换下拉菜单
        function toggleDropdown() {
            const dropdown = document.getElementById('dropdown');
            dropdown.classList.toggle('show');
        }

        // 退出登录
        function logout() {
            localStorage.removeItem('phoneNumber');
            window.location.href = 'index.html';
        }

        // 点击其他地方关闭下拉菜单
        window.onclick = function(event) {
            if (!event.target.matches('.user-phone')) {
                const dropdown = document.getElementById('dropdown');
                if (dropdown.classList.contains('show')) {
                    dropdown.classList.remove('show');
                }
            }
        };

        // 打开创建任务弹窗
        function openCreateTaskModal() {
            // 清空表单
            document.getElementById('createTaskName').value = '';
            document.getElementById('createKeywords').value = '';
            document.getElementById('createExecuteInterval').value = '10';
            document.getElementById('createPostTimeLimit').value = '4';
            document.getElementById('createSearchPages').value = '1'; // 清空搜索页数
            document.getElementById('createTaskMessage').innerHTML = '';
            
            document.getElementById('createTaskModal').style.display = 'block';
        }

        // 关闭创建任务弹窗
        function closeCreateTaskModal() {
            document.getElementById('createTaskModal').style.display = 'none';
        }

        // 创建任务
        async function createTask() {
            const taskName = document.getElementById('createTaskName').value;
            const keywords = document.getElementById('createKeywords').value;
            const executeInterval = parseInt(document.getElementById('createExecuteInterval').value);
            const postTimeLimit = parseInt(document.getElementById('createPostTimeLimit').value);
            const searchPages = parseInt(document.getElementById('createSearchPages').value);
            const phoneNumber = localStorage.getItem('phoneNumber');
            
            if (!taskName || !keywords) {
                showMessage('createTaskMessage', '请输入任务名称和搜索关键词', 'error');
                return;
            }

            if (!executeInterval || executeInterval < 1) {
                showMessage('createTaskMessage', '请输入有效的执行间隔（最小1分钟）', 'error');
                return;
            }

            if (!postTimeLimit || postTimeLimit < 1) {
                showMessage('createTaskMessage', '请输入有效的帖子时间限制（最小1天）', 'error');
                return;
            }

            if (!searchPages || searchPages < 1) {
                showMessage('createTaskMessage', '请输入有效的搜索页数（最小1页）', 'error');
                return;
            }

            if (!phoneNumber) {
                showMessage('createTaskMessage', '请先登录', 'error');
                return;
            }

            showMessage('createTaskMessage', '创建任务中...', 'loading');

            try {
                // 将关键词字符串转换为数组
                const keywordArray = keywords.split(/[，,]/).map(k => k.trim()).filter(k => k);
                
                const response = await fetch('/xhs/api/task/create', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        phoneNumber: phoneNumber,
                        taskName: taskName,
                        keywords: keywordArray,
                        executeInterval: executeInterval,
                        postTimeLimit: postTimeLimit,
                        searchPages: searchPages
                    })
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    // 刷新任务列表
                    loadTasks();
                    // 直接关闭弹窗
                    closeCreateTaskModal();
                } else {
                    showMessage('createTaskMessage', data.message || '创建任务失败', 'error');
                }
            } catch (error) {
                showMessage('createTaskMessage', '网络错误，请重试', 'error');
                console.error('Error:', error);
            }
        }

        // 加载任务列表
        async function loadTasks() {
            const phoneNumber = localStorage.getItem('phoneNumber');
            
            if (!phoneNumber) {
                return;
            }

            try {
                // 加载所有任务数据，不分页
                const response = await fetch('/xhs/api/task/list', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        phoneNumber: phoneNumber,
                        pageNum: 1,
                        pageSize: 1000 // 获取所有数据
                    })
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    allTasks = data.data.records || [];
                    applyFilters(); // 应用筛选并显示
                } else {
                    console.error('获取任务列表失败:', data.message);
                }
            } catch (error) {
                console.error('获取任务列表失败:', error);
            }
        }

        // 应用筛选
        function applyFilters() {
            const statusFilter = document.getElementById('statusFilter').value;
            const enabledFilter = document.getElementById('enabledFilter').value;
            const sortFilter = document.getElementById('sortFilter').value;

            // 筛选数据
            filteredTasks = allTasks.filter(task => {
                let match = true;
                
                if (statusFilter && task.status !== statusFilter) {
                    match = false;
                }
                
                if (enabledFilter !== '' && task.enabled.toString() !== enabledFilter) {
                    match = false;
                }
                
                return match;
            });

            // 排序数据
            filteredTasks.sort((a, b) => {
                switch (sortFilter) {
                    case 'create_time_asc':
                        return new Date(a.createTime) - new Date(b.createTime);
                    case 'create_time_desc':
                        return new Date(b.createTime) - new Date(a.createTime);
                    case 'update_time_desc':
                        return new Date(b.updateTime) - new Date(a.updateTime);
                    case 'task_name_asc':
                        return a.taskName.localeCompare(b.taskName);
                    default:
                        return new Date(b.createTime) - new Date(a.createTime);
                }
            });

            // 重置分页
            currentPage = 1;
            totalPages = Math.ceil(filteredTasks.length / pageSize);
            
            // 显示当前页数据
            displayCurrentPage();
            updatePagination();
        }

        // 清空筛选
        function clearFilters() {
            document.getElementById('statusFilter').value = '';
            document.getElementById('enabledFilter').value = '';
            document.getElementById('sortFilter').value = 'create_time_desc';
            applyFilters();
        }

        // 显示当前页数据
        function displayCurrentPage() {
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const currentPageTasks = filteredTasks.slice(startIndex, endIndex);
            displayTasks(currentPageTasks);
        }

        // 显示任务列表
        function displayTasks(tasks) {
            const tasksList = document.getElementById('tasksList');
            
            if (!tasks || tasks.length === 0) {
                tasksList.innerHTML = '<div class="loading">暂无任务</div>';
                return;
            }

            tasksList.innerHTML = '';
            
            tasks.forEach(task => {
                const taskCard = document.createElement('div');
                taskCard.className = 'task-card';
                
                const statusClass = `status-${task.status.toLowerCase()}`;
                const statusText = getStatusText(task.status);
                const enabledClass = task.enabled === 1 ? 'status-enabled' : 'status-disabled';
                const enabledText = task.enabled === 1 ? '启用' : '禁用';
                
                // 解析关键词 - 直接使用字符串形式显示
                const keywords = task.keywords ? task.keywords.split(/[，,]/).map(k => k.trim()).filter(k => k) : [];
                
                taskCard.innerHTML = `
                    <div class="task-header">
                        <div class="task-name">${task.taskName}</div>
                        <div class="task-status-group">
                            <div class="task-status ${statusClass}">${statusText}</div>
                            <div class="task-enabled ${enabledClass}">${enabledText}</div>
                        </div>
                    </div>
                    <div class="task-info">创建时间: ${formatDate(task.createTime)}</div>
                    <div class="task-info">更新时间: ${formatDate(task.updateTime)}</div>
                    <div class="task-info">扫描到二维码: ${task.totalQrCodes || 0} 个</div>
                    <div class="task-info">执行间隔: ${task.executeInterval || 10} 分钟</div>
                    <div class="task-info">帖子时间限制: ${task.postTimeLimit || 4} 天</div>
                    <div class="task-info">搜索页数: ${task.searchPages || 1} 页</div>
                    ${task.lastExecuteTime ? `<div class="task-info">最后执行时间: ${formatDate(task.lastExecuteTime)}</div>` : ''}
                    ${task.status === 'FAILED' && task.errorMessage ? `<div class="task-info" style="color: #dc3545;">错误: ${task.errorMessage}</div>` : ''}
                    <div class="task-keywords">
                        ${keywords.map(keyword => `<span class="keyword-tag">${keyword}</span>`).join('')}
                    </div>
                    <div class="task-actions">
                        <button class="btn btn-primary btn-small" onclick="viewTaskResults(${task.id})">查看结果</button>
                        <button class="btn btn-warning btn-small" 
                                data-task-id="${task.id}" 
                                data-task-name="${task.taskName}" 
                                data-keywords="${task.keywords}" 
                                data-execute-interval="${task.executeInterval}" 
                                data-post-time-limit="${task.postTimeLimit}"
                                data-search-pages="${task.searchPages}"
                                onclick="openEditTaskModalFromButton(this)">修改</button>
                        <button class="btn btn-success btn-small" onclick="executeTask(${task.id})">立即执行</button>
                        <button class="btn btn-danger btn-small" onclick="deleteTask(${task.id})">删除</button>
                    </div>
                `;
                
                tasksList.appendChild(taskCard);
            });
        }

        // 更新分页
        function updatePagination() {
            const pagination = document.getElementById('pagination');
            
            if (totalPages <= 1) {
                pagination.innerHTML = '';
                return;
            }

            let paginationHTML = '';
            
            // 上一页
            paginationHTML += `<button ${currentPage === 1 ? 'disabled' : ''} onclick="changePage(${currentPage - 1})">上一页</button>`;
            
            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage) {
                    paginationHTML += `<button class="active">${i}</button>`;
                } else {
                    paginationHTML += `<button onclick="changePage(${i})">${i}</button>`;
                }
            }
            
            // 下一页
            paginationHTML += `<button ${currentPage === totalPages ? 'disabled' : ''} onclick="changePage(${currentPage + 1})">下一页</button>`;
            
            pagination.innerHTML = paginationHTML;
        }

        // 切换页码
        function changePage(page) {
            if (page < 1 || page > totalPages || page === currentPage) {
                return;
            }
            
            currentPage = page;
            displayCurrentPage();
            updatePagination();
        }

        // 刷新任务
        function refreshTasks() {
            currentPage = 1;
            loadTasks();
        }

        // 查看任务结果
        function viewTaskResults(taskId) {
            window.location.href = `result.html?taskId=${taskId}`;
        }

        let currentEditTaskId = null;

        // 从按钮打开修改任务弹窗
        function openEditTaskModalFromButton(button) {
            const taskId = parseInt(button.getAttribute('data-task-id'));
            const taskName = button.getAttribute('data-task-name');
            const keywords = button.getAttribute('data-keywords');
            const executeInterval = parseInt(button.getAttribute('data-execute-interval'));
            const postTimeLimit = parseInt(button.getAttribute('data-post-time-limit'));
            const searchPages = parseInt(button.getAttribute('data-search-pages'));
            
            openEditTaskModal(taskId, taskName, keywords, executeInterval, postTimeLimit, searchPages);
        }

        // 打开修改任务弹窗
        function openEditTaskModal(taskId, taskName, keywords, executeInterval, postTimeLimit, searchPages) {
            currentEditTaskId = taskId;
            
            document.getElementById('editTaskName').value = taskName || '';
            document.getElementById('editKeywords').value = keywords || '';
            document.getElementById('editExecuteInterval').value = executeInterval || 10;
            document.getElementById('editPostTimeLimit').value = postTimeLimit || 4;
            document.getElementById('editSearchPages').value = searchPages || 1; // 默认值为1
            document.getElementById('editTaskMessage').innerHTML = '';
            
            document.getElementById('editTaskModal').style.display = 'block';
        }

        // 关闭修改任务弹窗
        function closeEditTaskModal() {
            document.getElementById('editTaskModal').style.display = 'none';
            currentEditTaskId = null;
        }

        // 保存任务修改
        async function saveTaskChanges() {
            if (!currentEditTaskId) {
                showMessage('editTaskMessage', '任务ID不存在，请重新选择任务', 'error');
                return;
            }

            const phoneNumber = localStorage.getItem('phoneNumber');
            const keywords = document.getElementById('editKeywords').value.trim();
            const executeInterval = parseInt(document.getElementById('editExecuteInterval').value);
            const postTimeLimit = parseInt(document.getElementById('editPostTimeLimit').value);
            const searchPages = parseInt(document.getElementById('editSearchPages').value);

            if (!phoneNumber) {
                showMessage('editTaskMessage', '登录信息已过期，请重新登录', 'error');
                return;
            }

            if (!keywords) {
                showMessage('editTaskMessage', '关键词不能为空', 'error');
                return;
            }

            if (!executeInterval || executeInterval < 1) {
                showMessage('editTaskMessage', '请输入有效的执行间隔（最小1分钟）', 'error');
                return;
            }

            if (!postTimeLimit || postTimeLimit < 1) {
                showMessage('editTaskMessage', '请输入有效的帖子时间限制（最小1天）', 'error');
                return;
            }

            if (!searchPages || searchPages < 1) {
                showMessage('editTaskMessage', '请输入有效的搜索页数（最小1页）', 'error');
                return;
            }

            showMessage('editTaskMessage', '保存中...', 'loading');

            try {
                const response = await fetch('/xhs/api/task/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        phoneNumber: phoneNumber,
                        taskId: parseInt(currentEditTaskId),
                        keywords: keywords,
                        executeInterval: executeInterval,
                        postTimeLimit: postTimeLimit,
                        searchPages: searchPages
                    })
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    loadTasks(); // 重新加载任务列表
                    closeEditTaskModal(); // 直接关闭弹窗
                } else {
                    showMessage('editTaskMessage', data.message || '修改失败', 'error');
                }
            } catch (error) {
                console.error('修改任务失败:', error);
                showMessage('editTaskMessage', '修改失败，请检查网络连接或重试', 'error');
            }
        }

        // 删除任务
        async function deleteTask(taskId) {
            if (!confirm('确定要删除这个任务吗？\n删除后将无法恢复，包括所有相关的扫描结果。')) {
                return;
            }

            const phoneNumber = localStorage.getItem('phoneNumber');

            if (!phoneNumber) {
                alert('请先登录');
                return;
            }

            try {
                const response = await fetch('/xhs/api/task/delete', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        phoneNumber: phoneNumber,
                        taskId: taskId
                    })
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    alert('任务删除成功');
                    loadTasks(); // 重新加载任务列表
                } else {
                    alert('删除失败: ' + data.message);
                }
            } catch (error) {
                console.error('删除任务失败:', error);
                alert('删除失败，请重试');
            }
        }

        // 立即执行任务
        async function executeTask(taskId) {
            if (!confirm('确定要立即执行这个任务吗？')) {
                return;
            }
            
            const phoneNumber = localStorage.getItem('phoneNumber');
            
            if (!phoneNumber) {
                alert('请先登录');
                return;
            }

            try {
                const response = await fetch('/xhs/api/task/execute', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        phoneNumber: phoneNumber,
                        taskId: taskId
                    })
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    alert('任务已开始执行');
                    // 刷新任务列表
                    loadTasks();
                } else {
                    alert('执行任务失败: ' + data.message);
                }
            } catch (error) {
                alert('执行任务失败: ' + error.message);
            }
        }



        // 获取状态文本
        function getStatusText(status) {
            const statusMap = {
                'PENDING': '待执行',
                'RUNNING': '执行中',
                'COMPLETED': '已完成',
                'FAILED': '失败'
            };
            return statusMap[status] || status;
        }

        // 格式化日期
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 点击弹窗外部关闭
        window.addEventListener('click', function(event) {
            const createModal = document.getElementById('createTaskModal');
            const editModal = document.getElementById('editTaskModal');
            
            if (event.target === createModal) {
                closeCreateTaskModal();
            }
            if (event.target === editModal) {
                closeEditTaskModal();
            }
        });

        // 显示消息
        function showMessage(elementId, message, type) {
            const element = document.getElementById(elementId);
            element.innerHTML = `<div class="${type}">${message}</div>`;
            
            if (type === 'success') {
                setTimeout(() => {
                    element.innerHTML = '';
                }, 3000);
            }
        }
    </script>
</body>
</html> 